<?php
/**
 * Created by PhpStorm.
 * User: Egg
 * Date: 2018/4/11
 * Time: 9:55
 */

namespace Admin\Model;


use Common\Common\HttpUtil;
use Org\Util\Date;
use Wechat\Model\WxLogic;

class WxResourceLogic
{
    /**
     * 获取微信素材
     * @param $type     除news的类型 image，voice，video
     * @return array
     */
    public function get_wx_res($type)
    {
        $url = C('url_wx_res_list') . WxLogic::getAccessToken();
        $index = 0;
        $data = array();
        $post_data['type'] = $type;
        $post_data['count'] = 20;
        for ($i = 0; ; $i++) {
            $post_data['offset'] = $index;

            $result = HttpUtil::https_request($url, json_encode($post_data));
            $result = '{
                   "total_count": 40,
                   "item_count": 20,
                   "item": [{
                       "media_id": ' . $i . ',
                       "name":  ' . $i . ',
                       "update_time":  "' . time() . '",
                       "url":"www.baidu.com"
                   }
                   ]
                }';
            $result = json_decode($result, true);
            //当接口请求出错时
            if (array_key_exists('errcode', $result)) {
                break;
            }
            //合并数组
            $data = array_merge($data, $result['item']);
            $index += 20;
            if ($index >= $result['total_count']) {
                break;
            }
        }
        return $data;
    }

    /**
     * 判断media_id是否存在
     * @param $media_id     对象media_id
     * @param $db           数据库连接
     * @return bool
     */
    public function is_exit($media_id, $db)
    {
        $where['media_id'] = $media_id;
        $result = $db->where($where)->find();
        if (empty($result)) {
            return false;
        } else {
            return true;
        }
    }

}